#include <QCoreApplication>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("124.71.214.151");
    db.setUserName("qtmysql");
    db.setPassword("asdw");
    db.setDatabaseName("qtmysql");
    if (!db.open()) {
        qDebug() << "Failed to connect to database:" << db.lastError().text();
        return -1;
    }else{
        qDebug() << "Successfully connected to database";
    }
    QSqlQuery query;
    if (query.exec("CREATE TABLE mytable (id INT PRIMARY KEY, name VARCHAR(20))")) {
        qDebug() << "创建了表";
    }else{
        qDebug() << "创建表失败，可能已经存在";
    }
    query.prepare("INSERT INTO mytable (id, name) VALUES (:id, :name)");
    query.bindValue(":id", 2);
    query.bindValue(":name", "汪涵");
    if (query.exec()) {
        qDebug() << "插入成功";
    } else {
        qDebug() << "插入失败:" << query.lastError().text();
    }

    // Check if the data has been inserted
    if (query.exec("SELECT * FROM mytable")) {
        while (query.next()) {
            qDebug() << query.value(0).toInt() << query.value(1).toString();
        }
    }else{
        qDebug() << "查询失败";
    }

    return 0;
}
